package com.ebay.contest.gfour.mapapi;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Scanner;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ebay.contest.gfour.common.GeoLocation;

/**
 * Application Lifecycle Listener implementation class
 * PopulateZipCodeMapListener
 * 
 */
public class PopulateZipCodeMapListener implements ServletContextListener {

	/**
	 * Default constructor.
	 */
	public PopulateZipCodeMapListener() {
	}

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		ApplicationContext beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(sce
				.getServletContext());
		String zipCodeDatabaseFilePath = (String) beanFactory.getBean("zipCodeDatabaseFilePath");
		@SuppressWarnings("unchecked")
		HashMap<Integer, GeoLocation> zipCodeMapper = (HashMap<Integer, GeoLocation>) beanFactory
				.getBean("zipCodeMapper");
		InputStream stream = sce.getServletContext().getResourceAsStream(zipCodeDatabaseFilePath);
		Scanner scanner = new Scanner(new BufferedInputStream(stream));
		while (scanner.hasNextLine()) {
			String[] line = scanner.nextLine().split(",");
			Integer zipCode = Integer.parseInt(line[0]);
			double latitude = Double.parseDouble(line[1]);
			double longtitude = Double.parseDouble(line[2]);
			zipCodeMapper.put(zipCode, new GeoLocation(latitude, longtitude));
		}
		scanner.close();
	}

	/**
	 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
	}

}
